package service

import (
	"github.com/go-xorm/xorm"

	"im/errcode"
	"im/model"
	"im/requests"
	"im/responses"
	"im/service/orm"
)

type GroupsMessagesService struct {
	db *xorm.Engine
}

func NewGroupsMessagesService() *GroupsMessagesService {
	return &GroupsMessagesService{db: orm.GetDB()}
}

func (s *GroupsMessagesService) GetList(appId uint, groupId int64, param requests.GetMessages) (responses.GetGroupsMessages, error) {
	var (
		list    = []model.GroupsMessages{}
		session = &xorm.Session{}
		err     error
		resp    = responses.GetGroupsMessages{
			Cursor: param.Cursor,
		}
	)

	session = s.db.Where("apps_id=?", appId)
	session = session.Where("`to`=?", groupId)
	session = session.Where("created>=?", param.BeginTime)
	session = session.Where("id>?", param.Cursor)
	if !param.EndTime.IsZero() {
		session = session.Where("created<=?", param.EndTime)
	}

	session = session.Desc("id")
	session = session.Limit(param.Limit)
	err = session.Find(&list)
	if err != nil {
		return resp, errcode.NewError(errcode.DaoFailed, err)
	}
	resp.List = list
	if len(list) > 0 {
		resp.Cursor = int(list[0].Id)
	}
	return resp, nil
}
